package com.bestcem.xm.member.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.member.controller.param.HttpMemberBaseParam;
import com.bestcem.xm.member.dao.MemberDao;
import com.bestcem.xm.member.entity.mongo.ExtendFieldValue;
import com.bestcem.xm.member.entity.mysql.LabelValueId;
import com.bestcem.xm.member.entity.pojo.MemberDO;
import com.bestcem.xm.member.enums.MemberTypeEnum;
import com.bestcem.xm.member.grpc.client.XmMemberClient;
import com.bestcem.xm.member.mq.message.MemberDeletedMessage;
import com.bestcem.xm.member.mq.message.MemberMessage;
import com.bestcem.xm.member.service.dto.OrganizationDTO;
import com.bestcem.xm.member.service.mq.send.MemberMessageSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

import static com.bestcem.xm.member.constant.Constants.EMPLOYEE_STATUS_MAP;

/**
 * 联系人工具类
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/8/25
 */
@Slf4j
@Component
public class MemberUtil {

    @Resource
    private MemberDao memberDao;

//    @Resource
//    private RabbitMessageSender rabbitMessageSender;

    @Resource
    private XmMemberClient xmMemberClient;

//    @Autowired
//    private RabbitMqConstantConfig rabbitMqConstantConfig;

    @Autowired
    private MemberMessageSendService memberMessageSendService;

    /**
     * 处理 手机号
     *
     * @param mobile
     * @param displayContact
     * @return
     */
    public static String handleMobile(String mobile, Boolean displayContact) {
        if (StrUtil.isNotEmpty(mobile) && !displayContact) {
            // 不展示
            return StrUtil.hide(mobile, 4, 8);
        }
        return mobile;
    }

    /**
     * 处理邮箱
     *
     * @param email
     * @param displayContact
     * @return
     */
    public static String handleEmail(String email, Boolean displayContact) {
        if (StrUtil.isNotEmpty(email) && !displayContact) {
            // 不展示
            return "****" + email.substring(email.indexOf("@"));
        }
        return email;
    }

    /**
     * 获取证件类型
     *
     * @param mobile
     * @param orgId
     * @param email
     * @return
     */
    public String getIdentityType(String mobile, String orgId, String email) {
        String identityType = "非员工";
        if (StrUtil.isNotEmpty(mobile)) {
            MemberDO interior = memberDao.findByOrgIdAndFieldAndMemberType(orgId, "phone", mobile, MemberTypeEnum.INTERIOR.getIndex());
            if (ObjectUtil.isNotEmpty(interior)) {
                identityType = ObjectUtil.isNotEmpty(interior.getEmployeeStatus()) ? EMPLOYEE_STATUS_MAP.get(interior.getEmployeeStatus()) : "";
            } else {
                if (StrUtil.isNotEmpty(email)) {
                    interior = memberDao.findByOrgIdAndFieldAndMemberType(orgId, "email", email, MemberTypeEnum.INTERIOR.getIndex());
                    if (ObjectUtil.isNotEmpty(interior)) {
                        identityType = ObjectUtil.isNotEmpty(interior.getEmployeeStatus()) ? EMPLOYEE_STATUS_MAP.get(interior.getEmployeeStatus()) : "";
                    }
                }
            }
        }
        return identityType;
    }

    /**
     * 推送创建的联系人
     *
     * @param message
     */
    public void publishCreateMember(MemberMessage message) {
        // 时间-8h 因为mongo中存储的是北京时间
        if (ObjectUtil.isNotEmpty(message.getCreateTime())) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(message.getCreateTime());
            // calendar.add(Calendar.HOUR, -8);
            Date time = calendar.getTime();
            message.setCreatedDt(DateUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
        }

        if (ObjectUtil.isNotEmpty(message.getUpdateTime())) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(message.getUpdateTime());
            // calendar.add(Calendar.HOUR, -8);
            Date time = calendar.getTime();
            message.setUpdatedDt(DateUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
        }
        if (log.isInfoEnabled()) {
            log.info("推送创建的联系人 {}", JSONObject.toJSONString(message));
        }
        // 推送创建的联系人
//        try {
//            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), null,
//                    MemberMqConstant.MEMBER_CREATE, message);
//        } catch (Exception e) {
//            log.error("推送创建的联系人失败 {} ", JSONObject.toJSONString(message), e);
//        }
        //stream mq 2022/05/12
        memberMessageSendService.memberCreatedSend(message);
    }

    /**
     * 推送更新的联系人
     *
     * @param message
     */
    public void publishUpdateMember(MemberMessage message) {

        if (ObjectUtil.isNotEmpty(message.getCreateTime())) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(message.getCreateTime());
            // calendar.add(Calendar.HOUR, -8);
            Date time = calendar.getTime();
            message.setCreatedDt(DateUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
        }

        if (ObjectUtil.isNotEmpty(message.getUpdateTime())) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(message.getUpdateTime());
            // calendar.add(Calendar.HOUR, -8);
            Date time = calendar.getTime();
            message.setUpdatedDt(DateUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
        }
        if (log.isInfoEnabled()) {
            log.info("推送更新的联系人 {}", JSONObject.toJSONString(message));
        }
        // 推送创建的联系人
        try {
//            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), null,
//                    MemberMqConstant.MEMBER_UPDATE, message);
            //stream mq 2022/05/12
            memberMessageSendService.memberUpdatedSend(message);
        } catch (Exception e) {
            log.error("推送更新的联系人失败 {} ", JSONObject.toJSONString(message), e);
        }
    }

    /**
     * 推送删除的联系人
     *
     * @param message
     */
//    public void publishDeleteMember(MemberMessage message) {
//        if (log.isInfoEnabled()) {
//            log.info("开始发送消息 {}", JSONObject.toJSONString(message));
//        }
//        // 推送创建的联系人
////        try {
////            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), null,
////                    MemberMqConstant.MEMBER_DELETE, message);
////        } catch (Exception e) {
////            log.error("推送删除的联系人失败 {} ", JSONObject.toJSONString(message), e);
////        }
//        memberMessageSendService.memberDeletedFanoutSend(message);
//    }

    /**
     * 推送删除的联系人
     *
     * @param ids
     * @param data
     * @param orgId
     */
    public void publishDeleteMember(List<String> ids, OrganizationDTO data, String orgId) {
        if (CollUtil.isNotEmpty(ids)) {
            MemberDeletedMessage message = new MemberDeletedMessage();
            message.setIds(ids);
            message.setOrgId(orgId);
            message.setOrgCode(data.getCode());
            message.setOrgName(data.getName());
            if (log.isInfoEnabled()) {
                log.info("开始发送消息 {}", JSONObject.toJSONString(message));
            }
            // 推送创建的联系人
//            try {
//                rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppBpMemberMemberDeletedExchange(), rabbitMqConstantConfig.getAppBpMemberMemberDeletedRoutingKey(),
//                        "member.member_delete", message);
//            } catch (Exception e) {
//                log.error("推送删除的联系人失败 {} ", JSONObject.toJSONString(message), e);
//            }

            //stream mq /2022.05.10
            memberMessageSendService.memberDeletedSend(message);
        }
    }

    /**
     * 获取组织信息
     *
     * @param orgId
     */
    public ServiceResult<OrganizationDTO> getOrganization(String orgId) {
        return xmMemberClient.getOrgByIdOrCode(orgId, null);
    }

    public Map<String, JSONObject> getStoreMap(String orgId) {
        Map<String, JSONObject> storeMap = new HashMap<>();
        ServiceResult<JSONObject> result = xmMemberClient.getStoreIdNameMap(orgId);
        if (!result.isSuccess()) {
            log.error("获取该组织 {} 的门店信息映射失败 {}", orgId, result.getMsg());
            return storeMap;
        }
        JSONObject data = result.getData();
        if (!data.isEmpty()) {
            data.keySet().forEach(key -> {
                storeMap.put(key, (JSONObject) data.get(key));
            });
        }
        return storeMap;
    }

    public static MemberDO httpMemberBaseParamToMemberDo(HttpMemberBaseParam param) {
        MemberDO memberDo = new MemberDO();
        memberDo.setOrgId(param.getOrgId());
        memberDo.setSysId(param.getSysId());
        memberDo.setSource(param.getSource());
        memberDo.setName(param.getName());
        memberDo.setEmail(param.getEmail());
        memberDo.setPhone(param.getMobile());
        memberDo.setGender(param.getGender());
        memberDo.setStoreId(param.getStore());
        memberDo.setStatus(param.getStatus());
        memberDo.setContent(param.getContent());
        memberDo.setOpenId(param.getOpenId());
        memberDo.setAppId(param.getAppId());
        memberDo.setMemberNo(param.getMemberNo());
        memberDo.setAliPayUserId(param.getAlipayUserId());
        memberDo.setAddress(JSONObject.toJSONString(param.getAddress()));
        memberDo.setEmployeeId(param.getEmployeeId());
        memberDo.setEmployeeStatus(param.getEmployeeStatus());
        memberDo.setMemberType(param.getMemberType());
        if (StrUtil.isNotEmpty(param.getBirthday())) {
            memberDo.setBirthday(DateUtil.parse(param.getBirthday()).toJdkDate());
        }
        memberDo.setDepartment(param.getDepartment());
        memberDo.setPosition(param.getPosition());
        memberDo.setInstituteName(param.getInstituteName());
        memberDo.setInstituteId(param.getInstituteId());
        memberDo.setFieldValList(JSONObject.toJSONString(param.getFieldValues()));
        memberDo.setUserId(param.getUserId());
        memberDo.setAge(param.getAge());
        memberDo.setLabels(JSONObject.toJSONString(param.getLabels()));
        memberDo.setUpdateTime(com.bestcem.xm.common.core.uitls.DateUtil.getCommonDate());
        memberDo.setCreateTime(memberDo.getUpdateTime());
        memberDo.setRegion(param.getRegion());
        memberDo.setOutNo(param.getOutNo());
        return memberDo;
    }

    /**
     * MemberDo to MemberMessage
     *
     * @param member
     * @return
     */
    public static MemberMessage memberDoToMemberMessage(MemberDO member) {
        MemberMessage memberMessage = new MemberMessage();
        memberMessage.setId(member.getId());
        memberMessage.setOrgId(member.getOrgId());
        memberMessage.setSysId(member.getSysId());
        memberMessage.setSource(member.getSource());
        memberMessage.setName(member.getName());
        memberMessage.setEmail(member.getEmail());
        memberMessage.setMobile(member.getPhone());
        memberMessage.setGender(member.getGender());
        memberMessage.setStore(member.getStoreId());
        memberMessage.setStatus(member.getStatus());
        memberMessage.setContent(member.getContent());
        memberMessage.setOpenId(member.getOpenId());
        memberMessage.setAppId(member.getAppId());
        memberMessage.setAlipayUserId(member.getAliPayUserId());
        memberMessage.setMemberNo(member.getMemberNo());
        memberMessage.setAddress(JSONObject.parseArray(member.getAddress(), String.class));
        memberMessage.setEmployeeId(member.getEmployeeId());
        memberMessage.setEmployeeStatus(member.getEmployeeStatus());
        memberMessage.setMemberType(member.getMemberType());
        memberMessage.setBirthday(member.getBirthday());
        memberMessage.setDepartment(member.getDepartment());
        memberMessage.setPosition(member.getPosition());
        memberMessage.setInstituteId(member.getInstituteId());
        memberMessage.setInstituteName(member.getInstituteName());
        memberMessage.setUserId(member.getUserId());
        memberMessage.setAge(member.getAge());
        memberMessage.setUpdateTime(member.getUpdateTime());
        memberMessage.setCreateTime(member.getCreateTime());
        memberMessage.setUnionId(member.getUnionId());
        memberMessage.setOutNo(member.getOutNo());
        memberMessage.setAvatar(member.getAvatar());
        if (StrUtil.isNotEmpty(member.getLabels())) {
            memberMessage.setLabels(JSONArray.parseArray(member.getLabels(), LabelValueId.class));
        }
        if (StrUtil.isNotEmpty(member.getFieldValList())) {
            memberMessage.setFieldValList(JSONArray.parseArray(member.getFieldValList(), ExtendFieldValue.class));
        }
        return memberMessage;
    }

    /**
     * 检查联系人数量
     *
     * @param orgId
     * @return
     */
    public ServiceResult<String> checkMemberNumber(String orgId) {
        // 获取该账号限制的联系人数量
        ServiceResult<Integer> userPackageQuota =
                xmMemberClient.getUserPackageQuota(orgId);
        if (!userPackageQuota.isSuccess()) {
            return ServiceResult.<String>fail("服务调用失败").setErrorCode("-1");
        }
        Integer createMemberNum = userPackageQuota.getData();
        if (log.isInfoEnabled()) {
            log.info("该组织 {} 个人联系人的配额 {}", orgId, createMemberNum);
        }
        if (createMemberNum != -1) {
            // 获取个人联系人的数量
            Long num = memberDao.countIndividualMember(orgId);
            if (log.isInfoEnabled()) {
                log.info("该组织 {} 个人联系人的数量 {}", orgId, num);
            }
            if (num >= createMemberNum) {
                return ServiceResult.<String>fail("已达套餐限额").setErrorCode("-1");
            }
        }
        return ServiceResult.success();
    }
}
